import React, { PureComponent } from 'react';
// 引入框架
import { message, Input, Button, Modal } from 'antd';
// 引入请求
import Axios from 'axios';
// 引入接口
import { webSite } from '../../website';
import './kingfanopera.scss';
export default class Kingfanopera extends PureComponent {
  constructor() {
    super()
    this.state = {
      // 显示
      isTrue: false,
      // 番剧名
      fanName: '',
      // 番剧封面
      fanImg: '',
      // 添加集数
      index: 2,
      // 番剧列表
      fanList: [],
      // 番剧列表对话框是否显示
      visible: false,
      // 对话框的番剧名
      listName: '',
      // 对话框的番剧url
      listUrl: '',
      // 显示几个input框
      listIndex: [],
      // 对话框的id
      fanId: 0
    }
  }
  componentDidMount () {
    const _this = this;
    if (sessionStorage.getItem('password')) {
      Axios.create({
        baseURL: `${webSite}:3003`
      }).post("/King", { password: sessionStorage.getItem('password') }).then(err => {
        if (err.data.code === 'K0001') {
          // 密码正确显示页面
          _this.setState({
            isTrue: true
          }, () => {
            this.getFan()
          })
        } else {
          // 没有网络连接就返回管理员页面
          _this.props.history.replace('/king');
        }
      }).catch(() => {
        // 没有网络连接就返回管理员页面
        this.props.history.replace('/king');
      })
    } else {
      // 没有密码就返回管理员页面
      this.props.history.replace('/king');
    }
  }
  // input的输入事件
  handleInput = ({ target }) => {
    let { name, value } = target
    // 设置input和state同步
    this.setState({
      [name]: value
    })
  }
  // 获取番剧
  getFan = () => {
    const _this = this;
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/getFanopera").then(err => {
      if (err.data.code === 'F0001') {
        _this.setState({
          fanList: err.data.list
        })
      }
    }).catch(() => {
      message.error({ content: '请检查您的网络连接', className: 'bulletChatMessage' });
    })
  }
  // 添加集数
  addFan = () => {
    let { index } = this.state;
    // 添加集数
    this.setState({
      index: index + 1
    }, () => {
      // 创建一个空的div
      let div = document.createElement('div');
      // div中写入input
      div.innerHTML = `
      <input placeholder="第${index}集链接" class='get${index} ant-input wallInput' name='get${index}' autocomplete="off" />
    `;
      // 获取包裹元素
      let DivNode = document.getElementsByClassName('kingfanopera_addFan_body_input')[0];
      // 把创建的元素添加到div
      DivNode.appendChild(div);
    })
  }
  // 删除集数
  deleteFan = () => {
    let { index } = this.state;
    // 判断保留一集
    if (index >= 3) {
      this.setState({
        index: index - 1
      }, () => {
        // 删除现有集数的最后一个
        let boxdelete = document.getElementsByClassName(`get${index - 1}`)[0];
        boxdelete.remove();
      })
    } else {
      message.info({ content: '您必须保留一集', className: 'bulletChatMessage' });
    }
  }
  // 提交番剧
  updataFan = () => {
    const _this = this;
    let { index } = this.state;
    // 判断是否有空格
    let fanName = this.state.fanName.replace(/\s+/g, "");
    let fanImg = this.state.fanImg.replace(/\s+/g, "");
    // 番剧名和封面不能是空
    if (!fanName) {
      message.info({ content: '番剧名不能是空', className: 'bulletChatMessage' });
      return;
    }
    if (!fanImg) {
      message.info({ content: '番剧封面不能是空', className: 'bulletChatMessage' });
      return;
    }
    // 番剧集数不能是空
    for (let i = 1; i < index; i++) {
      let fanListVal = document.getElementsByClassName(`get${i}`)[0].value.replace(/\s+/g, "");
      if (!fanListVal) {
        message.info({ content: `第${i}集的链接为空`, className: 'bulletChatMessage' });
        return;
      }
    }
    let fanAll = [];
    for (let i = 1; i < index; i++) {
      let fanObj = {}
      fanObj.fanColl = `第${i}集`
      fanObj.fanUrl = document.getElementsByClassName(`get${i}`)[0].value;
      fanAll.push(fanObj);
    }
    // 发送请求写入番剧
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/KingUpdataFan", { fanName: fanName, fanUrl: fanImg, fanList: JSON.stringify(fanAll) }).then(err => {
      if (err.data.code === 'A0001') {
        message.success({ content: '番剧写入成功', className: 'bulletChatMessage' })
        // 番剧写入成功之后重新拉取数据
        _this.getFan();
        // 清空所有输入框
        _this.setState({
          fanName: '',
          fanImg: ''
        })
        for (let i = 1; i < index; i++) {
          document.getElementsByClassName(`get${i}`)[0].value = '';
        }
      }
    }).catch(() => {
      // 没有网络连接就返回管理员页面
      message.info({ content: '没有网络连接，无法写入', className: 'bulletChatMessage' })
    })
  }
  // 删除某个番剧
  deleteFanId = (id) => {
    const _this = this;
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/deleteFanId", { id: id }).then(err => {
      if (err.data.code === 'D0001') {
        message.success({ content: '删除成功', className: 'bulletChatMessage' });
        // 删除成功之后重新获取一次函数
        _this.getFan();
      }
    }).catch(() => {
      // 没有网络连接就返回管理员页面
      message.info({ content: '没有网络连接，暂时无法删除', className: 'bulletChatMessage' })
    })
  }
  // 修改番剧信息
  updateFanList = (list) => {
    // 开启对话框
    this.setState({
      fanId: list.fanid,
      listName: list.fanName,
      listUrl: list.fanUrl,
      listIndex: JSON.parse(list.fanList),
      visible: true,
    });
  }
  // 关闭对话框
  handleCancel = () => {
    this.setState({
      visible: false,
      // 清空list
      listIndex: []
    });
  };
  // 修改番剧内容
  handleOk = () => {
    const _this = this;
    let { listName, listUrl, fanId, listIndex } = this.state;
    let fanAll = []
    for (let i = 1; i <= listIndex.length; i++) {
      let fanObj = {}
      fanObj.fanColl = `第${i}集`
      fanObj.fanUrl = document.getElementsByClassName(`true${i}`)[0].value;
      fanAll.push(fanObj);
    }
    Axios.create({
      baseURL: `${webSite}:3003`
    }).post("/KingUpdataFanlist", { id: fanId, fanName: listName, fanUrl: listUrl, fanList: JSON.stringify(fanAll) }).then(err => {
      if (err.data.code === 'U0001') {
        // 修改成功提示
        message.success({ content: '修改成功', className: 'bulletChatMessage' });
        // 关闭对话框
        _this.handleCancel();
        // 重新获取一次数据
        _this.getFan();
      }
    }).catch(() => {
      // 没有网络连接就返回管理员页面
      message.info({ content: '没有网络连接，无法修改', className: 'bulletChatMessage' })
    })
  }
  render () {
    let { fanList, listIndex } = this.state;
    // 把数组分成两份
    function group (array) {
      let newArray = [];
      let newArrayJI = [];
      let newArrayOU = [];
      for (let index = 0; index < array.length; index++) {
        if (index % 2 === 0) {
          newArrayJI.push(array[index])
        } else {
          newArrayOU.push(array[index])
        }
      }
      newArray.push(newArrayJI)
      newArray.push(newArrayOU)
      return newArray;
    }
    let list = group(fanList);
    return (
      <div className='kingfanopera'>
        {/* 番剧弹出框内容 */}
        <Modal
          visible={this.state.visible}
          onCancel={this.handleCancel}
          getContainer={() => document.getElementsByClassName('kingfanopera')[0]}
          className='kingfanopera_modal_fan'
          centered={true}
          bodyStyle={{
            height: '88%',
            overflow: 'auto'
          }}
          cancelText={'取消'}
          okText={'修改番剧'}
          onOk={this.handleOk}
        >
          {/* 番剧内容 */}
          <span className='kingfanopera_modal_fan_span'>番剧名</span>
          <Input placeholder="番剧名" className='wallInput' value={this.state.listName} name='listName' onChange={this.handleInput} autoComplete="off" />
          <span className='kingfanopera_modal_fan_span'>番剧封面</span>
          <Input placeholder="番剧封面" className='wallInput' value={this.state.listUrl} name='listUrl' onChange={this.handleInput} autoComplete="off" />
          <span className='kingfanopera_modal_fan_span'>番剧集数</span>
          {
            listIndex.length !== 0 ?
              listIndex.map((list, index) => {
                return (
                  <div key={index}>
                    <span className='kingfanopera_modal_fan_span'>{list.fanColl}</span>
                    <input placeholder={`第${index + 1}集链接`} defaultValue={list.fanUrl} className={`true${index + 1} ant-input wallInput`} name={`true${index + 1}`} autoComplete="off" />
                  </div>
                )
              })
              : ''
          }
        </Modal>
        {/* 添加番剧 */}
        <div className='kingfanopera_addFan'>
          <span>添加番剧</span>
          <div className='kingfanopera_addFan_body'>
            <div className='kingfanopera_addFan_body_title'>
              <p>番剧名</p>
              <p>番剧封面</p>
              <p>番剧集数链接</p>
              <Button type="primary" onClick={this.addFan} style={{ marginTop: '30px' }}>添加集数</Button>
              <Button type="primary" danger onClick={this.deleteFan}>删除集数</Button>
              <Button onClick={this.updataFan} style={{ background: '#70c3ff', color: '#ffffff' }}>提交番剧</Button>
            </div>
            <div className='kingfanopera_addFan_body_input'>
              <Input placeholder="番剧名" className='wallInput' value={this.state.fanName} name='fanName' onChange={this.handleInput} autoComplete="off" />
              <Input placeholder="番剧封面" className='wallInput' value={this.state.fanImg} name='fanImg' onChange={this.handleInput} autoComplete="off" />
              {/* 集数 */}
              <div>
                <input placeholder="第1集链接" className='get1 ant-input wallInput' name='get1' autoComplete="off" />
              </div>
            </div>
          </div>
        </div>
        {/* 已添加番剧 */}
        <div className='kingfanopera_addFan' style={{ marginTop: '40px' }}>
          <span>已有番剧</span>
          <div className='kingfanopera_fanList_body'>
            <ul className='kingfanopera_fanList_body_left'>
              {
                list[0].length !== 0 ?
                  list[0].map((list, index) => {
                    return (
                      <li key={index}>
                        <img src={list.fanUrl} alt="封面" />
                        <p>{list.fanName}</p>
                        <div className='kingfanopera_fanList_body_left_button'>
                          <Button type="primary" onClick={() => this.updateFanList(list)}>修改</Button>
                          <Button type="primary" danger onClick={() => this.deleteFanId(list.fanid)}>删除</Button>
                        </div>
                      </li>
                    )
                  })
                  : ''
              }
            </ul>
            <ul className='kingfanopera_fanList_body_right'>
              {
                list[1].length !== 0 ?
                  list[1].map((list, index) => {
                    return (
                      <li key={index}>
                        <img src={list.fanUrl} alt="封面" />
                        <p>{list.fanName}</p>
                        <div className='kingfanopera_fanList_body_left_button'>
                          <Button type="primary" onClick={() => this.updateFanList(list)}>修改</Button>
                          <Button type="primary" danger onClick={() => this.deleteFanId(list.fanid)}>删除</Button>
                        </div>
                      </li>
                    )
                  })
                  : ''
              }
            </ul>
          </div>
        </div>
      </div>
    )
  }
}